<template>
  <div class="comparison-table-container">
    <div class="comparison-header">
      <div class="header-title">对比数据</div>
      <div class="header-actions">
        <el-button type="primary" @click="handleExport">下载对比结果</el-button>
        <el-button @click="loadMoreData" :disabled="!hasMoreData" :loading="loadingMore">
          {{ loadingMore ? '加载中...' : '加载更多数据' }}
        </el-button>
      </div>
    </div>
    
    <div class="comparison-table-wrapper">
      <el-table
        v-loading="loading"
        :data="contrastData"
        border
        size="small"
        :span-method="objectSpanMethod"
        :header-cell-style="{background:'#f5f7fa',color:'#606266'}"
      >
        <el-table-column label="目/源类型" width="100" fixed="left">
          <template #default="scope">
            <el-tag :type="scope.row.type === 'target' ? 'primary' : 'success'" effect="plain">
              {{ scope.row.type === 'target' ? '目标数据' : '源数据' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column 
          v-for="(col, index) in dynamicColumns" 
          :key="index" 
          :prop="col" 
          :label="col"
          :min-width="120"
          :show-overflow-tooltip="true"
        >
          <template #default="scope">
            <span 
              :class="{ 
                'different-value': isDifferentValue(scope.row.groupId, col)
              }"
            >
              {{ formatValue(scope.row.data[col]) }}
            </span>
          </template>
        </el-table-column>
      </el-table>

      <div v-if="contrastData.length === 0 && !loading" class="no-data">
        暂无对比数据
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits, watch, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { getPairedComparisonData, exportContrastResult } from '@/api/data-sync';

const PAGE_SIZE = 100; // 每次加载100条数据

// 定义组件接收的属性
const props = defineProps({
  logId: {
    type: String,
    required: true
  }
});

// 定义组件触发的事件
const emit = defineEmits(['update:loading']);

// 加载状态
const loading = ref(false);
const loadingMore = ref(false);

// 对比数据
const contrastData = ref<any[]>([]);
const dynamicColumns = ref<string[]>([]);
const differentFields = ref<Map<string, Set<string>>>(new Map());
const currentOffset = ref(0);
const hasMoreData = ref(false);

// 处理单元格合并
const objectSpanMethod = ({ row, column, rowIndex }: any) => {
  // 如果是第一列（目/源类型列），每两行合并一次
  if (column.label === '目/源类型' && row.isFirstRow) {
    return {
      rowspan: 2,
      colspan: 1
    };
  } else if (column.label === '目/源类型' && !row.isFirstRow) {
    return {
      rowspan: 0,
      colspan: 0
    };
  }
  return null;
};

// 判断是否为不同值（需要高亮显示）
const isDifferentValue = (groupId: string, field: string) => {
  // 检查这一组的这个字段是否在不同字段列表中
  const diffFields = differentFields.value.get(groupId);
  return diffFields ? diffFields.has(field) : false;
};

// 格式化显示值
const formatValue = (value: any) => {
  if (value === null || value === undefined) {
    return '';
  }
  return value;
};

// 加载更多数据
const loadMoreData = async () => {
  if (!hasMoreData.value || loadingMore.value) return;
  
  loadingMore.value = true;
  try {
    await loadDataPage(currentOffset.value);
  } finally {
    loadingMore.value = false;
  }
};

// 加载指定页的数据
const loadDataPage = async (offset: number) => {
  if (!props.logId) return;
  
  try {
    if (offset === 0) {
      loading.value = true;
    }
    
    const response: any = await getPairedComparisonData(props.logId, offset, PAGE_SIZE);
    
    if (response.code === 200 && response.data) {
      const { target, source, different_fields, total, has_more } = response.data;
      
      if (target.length === 0) {
        ElMessage.warning('无目标数据');
        return;
      }
      
      // 处理数据差异信息
      processDataDifferences(different_fields);
      
      // 提取所有可能的列
      const allColumns = collectAllColumns(target, source);
      
      // 转换数据为表格格式并添加到现有数据中
      const newRows = transformDataToRows(target, source);
      
      if (offset === 0) {
        // 首次加载，替换数据
        contrastData.value = newRows;
        dynamicColumns.value = Array.from(allColumns);
      } else {
        // 加载更多，追加数据
        contrastData.value = [...contrastData.value, ...newRows];
      }
      
      // 更新分页信息
      currentOffset.value = offset + target.length;
      hasMoreData.value = has_more;
    } else {
      ElMessage.warning('无对比数据或数据加载失败');
      contrastData.value = [];
    }
  } catch (error) {
    console.error('加载对比数据失败:', error);
    ElMessage.error('加载对比数据失败');
  } finally {
    if (offset === 0) {
      loading.value = false;
    }
  }
};

// 处理数据差异信息
const processDataDifferences = (diffFields: any[]) => {
  if (!diffFields || diffFields.length === 0) return;
  
  // 按 target_id 分组不同字段
  diffFields.forEach(field => {
    const targetId = field.task_target_list_id;
    const groupId = `group_${targetId}`;
    const columnName = field.column_name;
    
    if (!differentFields.value.has(groupId)) {
      differentFields.value.set(groupId, new Set());
    }
    
    differentFields.value.get(groupId)?.add(columnName);
  });
};

// 收集所有可能的列
const collectAllColumns = (target: any[], source: any[]) => {
  const allColumns = new Set<string>();
  
  // 从目标数据收集列名
  target.forEach(item => {
    if (item.data) {
      Object.keys(item.data).forEach(key => allColumns.add(key));
    }
  });
  
  // 从源数据收集列名
  source.forEach(item => {
    if (item.data) {
      Object.keys(item.data).forEach(key => allColumns.add(key));
    }
  });
  
  return allColumns;
};

// 转换数据为表格行格式
const transformDataToRows = (target: any[], source: any[]) => {
  const rows: any[] = [];
  const sourceMap = new Map();
  
  // 创建源数据映射
  source.forEach(item => {
    sourceMap.set(item.task_target_list_id, item);
  });
  
  // 处理每一组目标数据和源数据
  target.forEach(targetItem => {
    const targetId = targetItem._id;
    const groupId = `group_${targetId}`;
    
    // 添加目标数据行
    rows.push({
      _id: targetId,
      type: 'target',
      data: targetItem.data || {},
      groupId,
      isFirstRow: true
    });
    
    // 查找对应的源数据
    const sourceItem = sourceMap.get(targetId);
    
    // 添加源数据行
    rows.push({
      _id: sourceItem ? sourceItem._id : null,
      type: 'source',
      data: sourceItem ? (sourceItem.data || {}) : {},
      groupId,
      isFirstRow: false
    });
  });
  
  return rows;
};

// 导出日志
const handleExport = () => {
  if (!props.logId) {
    ElMessage.warning('未找到日志ID，无法导出');
    return;
  }
  
  loading.value = true;
  ElMessage.info('正在准备下载文件，请稍候...');
  
  exportContrastResult(props.logId)
    .then(() => {
      ElMessage.success('导出成功');
    })
    .catch((error) => {
      console.error('导出失败:', error);
      ElMessage.error('导出失败：' + (error.message || '未知错误'));
    })
    .finally(() => {
      loading.value = false;
    });
};

// 监听logId变化重新加载数据
watch(() => props.logId, (newVal) => {
  if (newVal) {
    // 重置状态
    contrastData.value = [];
    dynamicColumns.value = [];
    differentFields.value = new Map();
    currentOffset.value = 0;
    hasMoreData.value = false;
    
    // 加载数据
    loadDataPage(0);
  }
}, { immediate: true });

// 暴露方法给父组件
defineExpose({
  loadMoreData,
  refresh: () => loadDataPage(0)
});
</script>

<style lang="scss" scoped>
.comparison-table-container {
  margin-top: 20px;
  
  .comparison-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    
    .header-title {
      font-size: 16px;
      font-weight: 500;
    }
  }
  
  .comparison-table-wrapper {
    margin-top: 15px;
    overflow-x: auto;
  }
  
  .no-data {
    text-align: center;
    color: #909399;
    padding: 30px 0;
  }
  
  :deep(.different-value) {
    color: #f56c6c;
    background-color: #fef0f0;
    padding: 2px 4px;
    border-radius: 2px;
  }
}
</style>